package com.internetCafes.spms.core.utils;

import com.sms.common.util.hutool.core.io.FileUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class FileUtils {

    public static final String JPG = ".JPG";

    public static final String PNG = ".PNG";

    public static final String DOC = ".DOC";

    public static final String DOCX = ".DOCX";

    public static final String XLS = ".XLS";

    public static final String XLSX = ".XLSX";

    public static final String PDF = ".PDF";

    public static final String RAR = ".RAR";

    public static final String ZIP = ".ZIP";

    /**
     * 转存
     *
     * @param file
     * @param basePath
     * @param fileName
     * @param maxSize
     * @param sizeUnit
     * @return
     */
    public static String transform(MultipartFile file, String basePath, String fileName, int maxSize, String sizeUnit, String[] fileTypes) throws Exception {
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (fileTypes != null && fileTypes.length > 0) {
            boolean isOk = false;
            String typeStr = "";
            for (String type : fileTypes) {
                typeStr += type;
                if (fileType.toUpperCase().equals(type)) {
                    isOk = true;
                }
            }
            if (!isOk) {
                throw new Exception("请上传" + typeStr + "格式的文件");
            }
        } else if (!fileType.toUpperCase().equals(JPG) && !fileType.toUpperCase().equals(PNG) &&
                !fileType.toUpperCase().equals(DOC) && !fileType.toUpperCase().equals(DOCX) &&
                !fileType.toUpperCase().equals(XLS) && !fileType.toUpperCase().equals(XLSX) &&
                !fileType.toUpperCase().equals(PDF) && !fileType.toUpperCase().equals(RAR) && !fileType.toUpperCase().equals(ZIP)) {
            throw new Exception("请上传jpg,png,xls,xlsx,doc,docx,pdf,rar,zip格式的文件");
        }

        if (!checkFileSize(file.getSize(), maxSize, sizeUnit)) {
            throw new Exception("照片大小不能超过" + maxSize + sizeUnit + "B");
        }

        if (StringUtils.isBlank(fileName)) {
            IdWorker id = new IdWorker(2);
            fileName = id.nextId() + "";
        }
        return transform(file, basePath, fileName);
    }


    /**
     * 转存
     *
     * @param file
     * @param basePath
     * @param fileName
     * @return
     */
    public static String transform(MultipartFile file, String basePath, String fileName) {
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File videoFilePath = new File(basePath);
        if (!videoFilePath.exists()) {
            videoFilePath.mkdirs();
        }

        if (StringUtils.isBlank(fileName)) {
            IdWorker id = new IdWorker(2);
            fileName = id.nextId() + "";
        }
        fileName = fileName + fileType;
        String filePath = basePath + File.separator + fileName;

        try {
            File oldFile = new File(filePath);
            oldFile.delete();
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }


    /**
     * 判断文件大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {

        if (size == 0) {
            return true;
        }

        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }


    public static String checkFileAttr(MultipartFile file, int size) {
        String resultStr = "";
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        if (!fileType.toUpperCase().equals(".JPG")) {
            resultStr = "请上传jpg格式的照片";
        }

        if (!checkFileSize(file.getSize(), size, "K")) {
            resultStr = "照片大小不能超过" + size + "Kb";
        }

        return resultStr;
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String pdfToJpg(MultipartFile multipartFile, String basePath,String fileName) throws Exception {

        PDDocument doc = PDDocument.load(multipartFileToFile(multipartFile));
        PDFRenderer pdfRenderer = new PDFRenderer(doc);
        BufferedImage bim = pdfRenderer.renderImageWithDPI(0, 200);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bim, "jpg", os);
        byte[] datas = os.toByteArray();
        //jpg文件转出路径
        File file = FileUtil.writeBytes(datas, new File(basePath + File.separator + fileName + ".jpg"));
        return fileName + ".jpg";
    }

}
